<template>
  <div class="amap-example">
    <!-- 左侧表单 -->
    <div class="pro-left-form" v-if="shouldShowField('search')">
      <LeftForm ref="leftFormRef" :search-config="props.searchConfig" :vco-types="props.vcoTypes" @search="onSearch"></LeftForm>
      <ProgressWrapper
        v-if="hasProgress"
        ref="progressWrapperRef"
        @play-click="onPlayClick"
        @play-stop="onStopClick"
        @resume-play="onResumeClick"
        @play-pause="onPauseClick"
      ></ProgressWrapper>
    </div>
    <div class="map-wrap">
      <!-- 地图基础 -->
      <AmapUI ref="amapUIRef" :opts="opts" :modules="modules" />
      <UpSvg v-if="shouldShowField('panel') && iconVisible" class="upIcon" @click.stop="handleOpenInfo"></UpSvg>
      <!-- 信息面板 -->
      <InfoPanel
        v-if="shouldShowField('panel')"
        ref="infoDrawerRef"
        :info="props.mapData"
        :panel-config="props.moduleConfig.panel"
        class="pro-info-panel"
        @visible-change="handleVisibleChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, watch } from "vue";
import ProgressWrapper from "./LeftWrapper/ProgressWrapper.vue";
import LeftForm from "./LeftWrapper/index.vue";
import InfoPanel from "./InfoPanel/index.vue";
// import AmapUI from "../AmapUI/index.vue";
import { AmapUI } from "@zszc/co-amapui-v3";
import { UpSvg } from "./images/index";
import { getInfoWindowTemplate } from "./InfoWindow/template";

// 定义接口
interface MapDataType {
  trackList: any[]; // 可根据实际数据结构替换 any 为更具体的类型
}

type ObjType = {
  isShow?: boolean;
  [props: string]: any;
};
interface Props {
  mapData: MapDataType;
  vcoTypes: {
    label: string;
    value: string;
  }[]; // 可根据实际数据结构替换 any 为更具体的类型
  // 搜索Item配置
  searchConfig?: {
    vno?: ObjType;
    vcoTypes?: ObjType;
    qryBtm?: ObjType;
    qryEtm?: ObjType;
    startLonlat?: ObjType;
    endLonlat?: ObjType;
    parkMins?: ObjType;
  };
  moduleConfig?: {
    search?: ObjType;
    panel?: {
      isShow?: boolean;
      trackList?: boolean;
      parkList?: boolean;
      cityList?: boolean;
    };
  };
}

// 使用 withDefaults 模式
const props = withDefaults(defineProps<Props>(), {
  mapData: () => ({
    trackList: []
  }),
  vcoTypes: (): { label: string; value: string }[] => [],
  searchConfig: () => ({
    vno: {},
    vcoTypes: {},
    qryBtm: {},
    qryEtm: {},
    startLonlat: {},
    endLonlat: {},
    parkMins: {}
  }),
  moduleConfig: () => ({
    search: {},
    panel: {}
  })
});

// 辅助函数，判断module是否显示
const shouldShowField = (field: keyof typeof props.moduleConfig) => {
  return props.moduleConfig[field]?.isShow !== false; // 默认显示，除非明确设置为false
};

// 定义emit函数
const emit = defineEmits(["search", "percentChange"]);

// 搜索
const searchInfo = ref();
const onSearch = (params: any) => {
  searchInfo.value = params;
  if (!params && leftFormRef.value) {
    searchInfo.value = leftFormRef.value.searchForm;
  }
  nextTick(() => {
    onStopClick();
    progressWrapperRef.value?.init(props.mapData.trackList.length);
    emit("search", params);
  });
};
const leftFormRef = ref<InstanceType<typeof LeftForm> | null>(null);
const setSearchForm = (params: any) => {
  leftFormRef.value?.setSearchForm(params);
};

// 进度条
const hasProgress = ref(false);
const progressWrapperRef = ref<InstanceType<typeof ProgressWrapper> | null>(null);

watch(
  () => props.mapData,
  newVal => {
    if (newVal) {
      handleLoad(newVal);
    }
  }
);

// 地图配置
const opts = reactive<any>({
  center: [116.397428, 39.90923],
  zoom: 4
});

const amapUIRef = ref<InstanceType<typeof AmapUI> | null>(null);

const polylineModules = ref<any>();
const modules = ref<any[]>([]);

// 加载地图
const handleLoad = async (options: any) => {
  if (!options || !options.trackList || !options.trackList.length) {
    return;
  }

  // WGS84 坐标 处理
  const path = options.trackList.map((item: any) => [item.lon / 600000, item.lat / 600000]);
  // 获取原数据，用于弹窗展示对应信息内容
  const origin = options.trackList.map(item => {
    return {
      ...item,
      lon: (item.lon / 600000).toFixed(7),
      lat: (item.lat / 600000).toFixed(7)
    };
  });

  // 设置停留点
  let stopovers = [];
  if (options && options.parkList && options.parkList.length) {
    stopovers = options.parkList.map(item => [item.parkLon / 600000, item.parkLat / 600000]);
  }

  modules.value = [
    {
      name: "Polyline",
      markers: [
        {
          path,
          strokeColor: "#409eff", //线颜色
          strokeOpacity: 1, //线透明度
          strokeWeight: 4, //线宽
          cursor: "pointer",
          extra: {
            origin, // 一条轨迹的原始数据
            stopovers, // 停留点
            infoWindowOpts: {
              // 自定义弹窗内容
              isCustom: true,
              closeWhenClickMap: true,
              content: (e: any) => getInfoWindowTemplate({ searchInfo, e })
            }
          }
        }
      ],
      extra: {
        coordTransform: "wgs84ToGcj02", // 转坐标
        isStopovers: true, // 是否开启显示停留点
        isLabeled: true, // 是否标注走过的点位
        isFence: {
          isOn: true, // 是否开启电子围栏
          fences: [
            {
              text: "发运地",
              center: [114.22451235317978, 37.15201972765679],
              radius: 5000,
              strokeColor: "#FF4D4F",
              strokeOpacity: 1,
              strokeWeight: 2,
              strokeStyle: "dashed" as const,
              strokeDasharray: [10, 10],
              fillOpacity: 0
            },
            {
              text: "发运地",
              center: [114.22451235317978, 37.15201972765679],
              radius: 10000,
              strokeColor: "#3398FF",
              strokeOpacity: 1,
              strokeWeight: 2,
              strokeStyle: "dashed" as const,
              strokeDasharray: [10, 10],
              fillOpacity: 0.3,
              fillColor: "#4AB616"
            },
            {
              text: "目的地",
              center: [114.8093398771129, 37.07019998836271],
              radius: 5000,
              strokeColor: "#FF4D4F",
              strokeOpacity: 1,
              strokeWeight: 2,
              strokeStyle: "dashed" as const,
              strokeDasharray: [10, 10],
              fillOpacity: 0
            },
            {
              text: "目的地",
              center: [114.8093398771129, 37.07019998836271],
              radius: 10000,
              strokeColor: "#3398FF",
              strokeOpacity: 1,
              strokeWeight: 2,
              strokeStyle: "dashed" as const,
              strokeDasharray: [10, 10],
              fillOpacity: 0.3,
              fillColor: "#4AB616"
            }
          ]
        }, // 电子围栏配置
        relieveInfoWindow: false // 是否禁用标注点弹窗
      }
    }
  ];
  nextTick(() => {
    amapUIRef.value?.loadModules().then(res => {
      hasProgress.value = true;

      console.log(res, "--=0-");
      // 确保res[0]和res[0].instance存在
      if (res && res[0] && res[0].moduleInstance) {
        polylineModules.value = res[0].moduleInstance; // 获取实例,用于播放，暂停，继续，停止

        // 注册percentChange事件监听
        res[0].moduleInstance?.instance.forEach(item => {
          item.on("percentChange", percent => {
            // emit("percentChange", percent); // 可在这里传输进度，控制倍速
            progressWrapperRef.value?.updateProgress(percent);
          });
        });
        // 绑定关闭信息窗口方法到window对象
        (window as any).closeInfoWindow = () => {
          const polylineModule = amapUIRef.value?.getModule("Polyline");
          console.log(polylineModule, "polylineModule");
          if (polylineModule && polylineModule.moduleInstance) {
            polylineModule.moduleInstance.events.closeInfoWindow();
          }
        };
      }
    });
  });
};

// 开始播放
const onPlayClick = (radio: number) => {
  if (!props.mapData || !props.mapData.trackList || !props.mapData.trackList.length) {
    console.warn("暂无轨迹");
    return;
  }
  console.log(polylineModules.value);
  polylineModules.value?.instance?.forEach(item => {
    item.methods.start(Math.floor(1000 / radio));
  });
  infoDrawerRef.value?.start(radio);
};

// 暂停播放
const onPauseClick = () => {
  polylineModules.value?.instance?.forEach(item => {
    item.methods.pause();
  });
  infoDrawerRef.value?.pause();
};

// 继续播放
const onResumeClick = (radio: number) => {
  polylineModules.value?.instance?.forEach(item => {
    item.methods.resume(Math.floor(1000 / radio));
  });
  infoDrawerRef.value?.start(radio);
};

// 停止播放
const onStopClick = () => {
  polylineModules.value?.instance?.forEach(item => {
    item.methods.stop();
  });
  infoDrawerRef.value?.stop();
};

// 信息面板
const iconVisible = ref(true);
const infoDrawerRef = ref();

const handleVisibleChange = (visible: boolean) => {
  iconVisible.value = !visible;
};
const handleOpenInfo = () => {
  infoDrawerRef.value.open();
};

defineExpose({
  onSearch,
  setSearchForm
});
</script>
<style lang="scss" scoped>
.amap-example {
  display: flex;
  align-items: flex-start;
  width: 100%;
  height: 100%;
  .pro-left-form {
    position: relative;
    width: 350px;
    height: 100%;
    padding: 20px 10px;
    background-color: #ffffff;
  }
  .map-wrap {
    position: relative;
    box-sizing: border-box;
    flex: auto;
    min-width: 960px;
    height: 100%;
    padding: 10px;
    margin-left: 10px;
    background-color: #f5f5f5;
  }

  /* 打开按钮样式 */
  .upIcon {
    position: absolute;
    bottom: 5px;
    left: 50%;
    z-index: 1500;
    width: 40px;
    height: 40px;
    cursor: pointer;
    transform: translateX(-50%);
    animation: wave 2s ease-in-out infinite;
  }
  .pro-info-panel {
    width: 100%;
  }
}

/* 波浪动画关键帧 */
@keyframes wave {
  0%,
  100% {
    transform: translateX(-50%) translateY(0);
  }
  25% {
    transform: translateX(-50%) translateY(-5px);
  }
  50% {
    transform: translateX(-50%) translateY(0);
  }
  75% {
    transform: translateX(-50%) translateY(-10px);
  }
}
</style>
